﻿
using Furion.Core;
using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using StackExchange.Profiling.Internal;
using System.Security.Claims;

namespace IdentityServer4CenterPassword
{
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {

        private readonly IRepository<User> _userRepository;

        private readonly IDistributedCache _cache;

        public ResourceOwnerPasswordValidator(IRepository<User> userRepository, IDistributedCache cache)
        {

            _userRepository = userRepository;
            _cache = cache;
        }


        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {


            var EncryptPassword = MD5Encryption.Encrypt(context.Password.Trim());
            var userInfo = await _userRepository.DetachedEntities.Where(a => a.UserName == context.UserName.Trim() && a.UserPass == EncryptPassword).FirstOrDefaultAsync();
            if (userInfo == null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "账号或密码错误");
            }
            else
            {
                if (userInfo.Enabled == false)
                {
                    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "账号被禁用");
                }
                else
                {


                    var cls = new Claim[]
                    {
                        new Claim(ClaimConst.CLAINM_USERID, userInfo.Id.ToString()),
                        new Claim(ClaimConst.CLAINM_ACCOUNT,userInfo.UserName),
                        new Claim(ClaimConst.CLAINM_NAME, userInfo.NickName)
                    };

                    context.Result = new GrantValidationResult(subject: userInfo.UserName, authenticationMethod: OidcConstants.AuthenticationMethods.Password, claims: cls);
                }

            }
        }


    }
}
